package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.dto.RedisData;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisCache;
import com.hmdp.utils.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.time.LocalDateTime;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisCache redisCache;

    //加锁
    private boolean addLock(String key){
        Boolean b = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(b);
    }

    //解锁
    private void releaseLock(String key){
        stringRedisTemplate.delete(key);
    }

    //查询数据库，重建缓存
    public void saveShopRedis(Long id , Long minute){
        String key = CACHE_SHOP_KEY + id;
        Shop shop = getById(id);
        RedisData redisData=new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusMinutes(minute));
        //写入redis
        stringRedisTemplate.opsForValue().set(key ,JSONUtil.toJsonStr(redisData));
    }

    /**
     * 根据id缓存商铺信息
     * @param id
     * @return
     */
    public Result queryById(Long id) {
        //互斥锁解决缓存击穿、存储null到缓存解决缓存穿透
        //Shop shop =queryWithLock(id);
        //采用逻辑时间解决缓存击穿
        //Shop shop =queryWithLogicTime(id);

        String key = CACHE_SHOP_KEY +id;
        //解决缓存穿透
        //Shop shop = redisCache.queryWithNull(key,id, Shop.class,CACHE_SHOP_TTL,TimeUnit.MINUTES, this::getById);

        //解决缓存击穿--使用互斥锁
        Shop shop = redisCache.queryWithLock(key, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        if(shop == null){
            return Result.fail("店铺id错误！");
        }

        return Result.ok(shop);
    }
    private final ExecutorService cacheRebuildExecutor = Executors.newFixedThreadPool(5);
    private Shop queryWithLogicTime(Long id){
        String key = CACHE_SHOP_KEY + id;
        //1 查询redis是否有商品信息
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        if(StrUtil.isBlank(shopJson)){
            //2 redis没数据，返回null
            return null;
        }
        //3 redis有数据,判断逻辑时间释放过期
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(),Shop.class);

        if(expireTime.isAfter(LocalDateTime.now())){
            //4 没过期
            log.info("数据没过期");
            return shop;
        }
        //5 过期了，需要开启线程，重建缓存
        log.info("数据已经过期");
        String keyLock = LOCK_SHOP_KEY + id;
        if(addLock(keyLock)){
            try {
                //5.1 加锁成功，开始再次查询缓存
                String laterShopJson = stringRedisTemplate.opsForValue().get(key);
                if(StrUtil.isNotBlank(laterShopJson)){
                    RedisData lateRedisData = JSONUtil.toBean(laterShopJson, RedisData.class);
                    LocalDateTime laterExpireTime = lateRedisData.getExpireTime();
                    Shop lateShop = JSONUtil.toBean((JSONObject) lateRedisData.getData(),Shop.class);
                    if(laterExpireTime.isAfter(LocalDateTime.now())){
                        //4 没过期,表明缓存已经重建
                        return lateShop;
                    }
                }

                //5.2 开启线程
                cacheRebuildExecutor.submit(()->{
                    try {
                        saveShopRedis(id,CACHE_SHOP_TTL);
                        log.info("缓存重建成功，店铺ID: {}", id);
                    } catch (Exception e) {
                        log.error("缓存重建失败:{}，店铺ID: {}",e,id);
                    }
                });
            } catch (Exception e) {
                throw new RuntimeException(e);
            }finally {
                //释放锁
                releaseLock(keyLock);
            }
        }

        //6 获得锁失败，返回旧数据
        return shop;
    }

    //互斥锁解决缓存击穿、存储null到缓存解决缓存穿透
    private Shop queryWithLock(Long id) {
        String key = CACHE_SHOP_KEY + id;

        //1.查询redis是否有商品信息
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        if(StrUtil.isNotBlank(shopJson)){
            //2.redis有数据，返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        //还要判断redis中是否是""  ----缓存穿透
        if("".equals(shopJson)){
            return null;
        }

        //3.redis为null，在mysql找----缓存击穿，用互斥锁解决
        Shop shop = null;
        String lockKey = LOCK_SHOP_KEY + id;
        try {
            //3.1 上锁
            boolean b = addLock(lockKey);
            if(!b){
                //获取锁失败
                Thread.sleep(50);
                return queryWithLock(id);
            }
            //3.2 查看缓存，因为其它线程可能已经重建缓存，防止再次查询数据库
            shopJson = stringRedisTemplate.opsForValue().get(key);
            if(StrUtil.isNotBlank(shopJson)){
                //redis有数据，返回
                shop = JSONUtil.toBean(shopJson, Shop.class);
                return shop;
            }
            //3.3 查询数据库
            shop = getById(id);
            if(shop == null){
                //4 没数据，防止缓存穿透，将""放入redis中
                stringRedisTemplate.opsForValue().set(key, "",CACHE_NULL_TTL,TimeUnit.MINUTES);
                return null;
            }
            //5.有数据,写入到redis
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL,TimeUnit.MINUTES);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            releaseLock(lockKey);
        }
        //6.返回数据
        return shop;
    }

    /**
     * 更新商铺信息
     * @param shop
     * @return
     */
    @Transactional
    public Result updateShop(Shop shop) {
        Long id = shop.getId();
        if(id == null ){
            return Result.fail("店铺id不能为空");
        }
        //先跟新数据库
        updateById(shop);

        //再删除redis数据
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + id);

        return Result.ok();
    }


}
